package com.jason.kotlin.notification

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import android.os.Build
import androidx.annotation.RequiresApi

object BitmapHelper {

    @SuppressLint("UseCompatLoadingForDrawables")
    fun drawableToBitmap(context: Context, resId: Int): Bitmap? {

        var drawable = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            context.getDrawable(resId)
        } else {
            context.resources.getDrawable(resId)
        }
        if (drawable != null) {
            return drawableToBitmap(drawable)
        }

        return BitmapFactory.decodeResource(context.resources, resId);
    }

    /**
     * 将drawable 转成bitmap
     *
     * @param drawable 需要转化的对象
     */
    private fun drawableToBitmap(drawable: Drawable): Bitmap {
        // 获取drawable的宽高
        val w = drawable.intrinsicWidth;
        val h = drawable.intrinsicHeight;

        // 取 drawable 的颜色格式
        val config =
            if (drawable.opacity !== PixelFormat.OPAQUE) Bitmap.Config.ARGB_8888 else Bitmap.Config.RGB_565
        // 建立对应 bitmap

        val bitmap = Bitmap.createBitmap(w, h, config)

        // 建立对应 bitmap 的画布
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, w, h)

        // 把 drawable 内容画到画布中
        drawable.draw(canvas)

        return bitmap
    }
}